import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:sinosheets/r.dart';

class NetworkImageWidget extends StatelessWidget {
  final String? url;
  final String? placeholder;
  final double? width;
  final double? height;
  final BoxFit fit;
  final BaseCacheManager? cacheManager;

  const NetworkImageWidget({
    super.key,
    this.url,
    this.width,
    this.height,
    this.placeholder,
    this.fit = BoxFit.cover,
    this.cacheManager,
  });

  @override
  Widget build(BuildContext context) {
    String actualUrl;
    bool isUrlExist;
    String actualPlaceholder;

    /// 判断url是否存在
    if ((url != null) && url!.isNotEmpty && (url!.length > 6)) {
      isUrlExist = true;
      actualUrl = url!;
    } else {
      isUrlExist = false;
      actualUrl = '';
    }

    /// url有可能以//开头，缺少https
    if (isUrlExist) {
      if (!actualUrl.startsWith('http')) {
        actualUrl = 'https:$actualUrl';
      }
    }

    /// 判断url是否有效
    bool isUrlValidate = false;
    if (isUrlExist) {
      Uri? uri = Uri.tryParse(actualUrl);
      if (uri != null) {
        var host = uri.host;
        if (host.isNotEmpty) {
          isUrlValidate = true;
        }
      }
    }

    /// 如果没有指定占位图，默认给一个
    actualPlaceholder = placeholder ?? R.assetsImgPlaceholderSearch;

    if (isUrlValidate) {
      return CachedNetworkImage(
        cacheManager: cacheManager ?? CustomCacheManager.instance,
        imageUrl: actualUrl,
        placeholder: (context, url) => _buildPlaceholderImage(actualPlaceholder),
        errorWidget: (context, url, error) => _buildPlaceholderImage(actualPlaceholder),
        width: width,
        height: height,
        fit: fit,
        fadeOutDuration: const Duration(milliseconds: 100),
        fadeInDuration: const Duration(milliseconds: 100),
        // //占位符,根据加载的进度显示进度条
        placeholderFadeInDuration: const Duration(seconds: 3),
      );
    } else {
      return _buildPlaceholderImage(actualPlaceholder);
    }
  }

  /// 占位图
  Widget _buildPlaceholderImage(String name) {
    return Image.asset(
      name,
      width: width,
      height: height,
      fit: BoxFit.fill,
    );
  }
}

class CustomCacheManager {
  static const key = 'all_image_cache';
  static CacheManager instance = CacheManager(
    Config(
      key,
      stalePeriod: const Duration(days: 3),
      maxNrOfCacheObjects: 200,
    ),
  );
}
